import { defineStore } from 'pinia'
import { login, getUserInfo, logout } from '../api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null
  }),

  actions: {
    // 登录
    async loginAction(loginForm) {
      try {
        const token = await login(loginForm)
        this.token = token
        localStorage.setItem('token', token)
        return token
      } catch (error) {
        throw error
      }
    },

    // 获取用户信息
    async getUserInfoAction() {
      try {
        const data = await getUserInfo()
        this.userInfo = data
        return data
      } catch (error) {
        throw error
      }
    },

    // 登出
    async logoutAction() {
      try {
        await logout()
        this.token = ''
        this.userInfo = null
        localStorage.removeItem('token')
      } catch (error) {
        throw error
      }
    },

    // 清除用户状态
    resetState() {
      this.token = ''
      this.userInfo = null
      localStorage.removeItem('token')
    }
  }
})